package com.whenjun.config.mybatis_handler;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;

/**
 * @ClassName: ArrayTypeHandler.java
 * @Description: mybatis TypeHandler 对mysql的com.alibaba.fastjson.JSONArray格式的类型转换
 *
 * @version: v1.0.0
 * @author: wanwenjun
 * @date: 2018年12月14日 上午11:13:58
 */
public class ArrayTypeHandler extends BaseTypeHandler<JSONArray>{

	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, JSONArray parameter, JdbcType jdbcType)
			throws SQLException {
		String json = JSON.toJSONString(parameter);
		ps.setString(i, json);
	}

	@Override
	public JSONArray getNullableResult(ResultSet rs, String columnName) throws SQLException {
		return parseArray(rs.getString(columnName));
	}

	@Override
	public JSONArray getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		return parseArray(rs.getString(columnIndex));
	}

	@Override
	public JSONArray getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		return parseArray(cs.getString(columnIndex));
	}

	private JSONArray parseArray(String json) {
        return JSON.parseArray(json);
    }
}
